package ltd.trackan.messagecenter.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import ltd.trackan.messagecenter.common.ValueCommon;
import ltd.trackan.messagecenter.model.coommon.RestBean;
import ltd.trackan.messagecenter.model.entity.Jdaccountinfo;
import ltd.trackan.messagecenter.service.JDAccountInfoService;
import ltd.trackan.messagecenter.mapper.JdaccountinfoMapper;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 实现
 * @author wxa
 */
@Service
@Slf4j
public class JDAccountInfoServiceImpl extends ServiceImpl<JdaccountinfoMapper, Jdaccountinfo>
        implements JDAccountInfoService {
    
    
    @Override
    public RestBean<String> updateAccountInfo(HashMap<String, String> hashMap) {
        if (ValueCommon.JD_ACCOUNT_MAPPER_ID.isEmpty()) {
            return RestBean.failure("请先更新京东账号信息");
        }
        try {
            // 对每个账号进行更新
            hashMap.forEach((account, content) -> {
                String s = ValueCommon.JD_ACCOUNT_MAPPER_ID.get(account);
                if (s != null) {
                    // 对内容转换成json
                    JSONObject jsonObject = new JSONObject();
                    // 账号内容的每行处理
                    String[] split = content.split("<br>");
                    for (String string : split) {
                        // 每行的标题
                        String title = null;
                        Pattern pattern = Pattern.compile("【(\\S*)】");
                        Matcher matcher = pattern.matcher(string);
                        while (matcher.find()) {
                            // 放入到双列集合里
                            title = matcher.group(1);
                        }
                        // 有分隔字段
                        if (title == null) {
                            continue;
                        }
                        // 每行的内容
                        String value = string.replace("【" + title + "】", "");
                        jsonObject.put(title, value);
                    }
                    // 更新信息
                    Jdaccountinfo set = new Jdaccountinfo();
                    set.setInfo(JSON.toJSONString(jsonObject));
                    Jdaccountinfo where = new Jdaccountinfo();
                    where.setUId(s);
                    if ( this.baseMapper.update(set, new UpdateWrapper<>(where))!=1) {
                        log.error("账号：{}，数据库更新信息失败！", account);
                    }
                }
            });
            return RestBean.success();
        } catch (Exception e) {
            log.error("更新数据库出现错误{}",e.getMessage());
            return RestBean.failure(e.getMessage());
        }
    }
}




